package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.kaishengit.entity.Admin;
import com.kaishengit.util.db.DBHelp;
import com.kaishengit.util.db.RowMapper;

public class AdminDao {

	public DBHelp<Admin> db = new DBHelp<Admin>();
	
	public void save(Admin admin) {
		String sql = "insert into t_admin(id,username,password,email,ip,role,lastaccesstime) values(?,?,?,?,?,?,?)";
		db.executeSQL(sql, admin.getId(),admin.getUsername(),admin.getPasswrod(),admin.getEmail(),admin.getIp(),admin.getRole(),admin.getLastaccessTime());
	}
	
	public void update(Admin admin) {
		String sql = "update t_admin set username = ?,password = ?,email = ?,ip = ?,role = ?,lastaccesstime=? where id = ?";
		db.executeSQL(sql, admin.getUsername(),admin.getPasswrod(),admin.getEmail(),admin.getIp(),admin.getRole(),admin.getLastaccessTime(),admin.getId());
	}
	
	public Admin findById(String id) {
		String sql = "select id,username,password,email,ip,role,lastaccesstime,createtime from t_admin where id = ?";
		return db.executeQueryToObject(sql, new AdminRowMapper(), id);
	}
	
	public Admin findByUserName(String username) {
		String sql = "select id,username,password,email,ip,role,lastaccesstime,createtime from t_admin where username = ?";
		return db.executeQueryToObject(sql, new AdminRowMapper(), username);
	}
	
	
	private class AdminRowMapper implements RowMapper<Admin> {

		public Admin mapRow(ResultSet rs) throws SQLException {
			Admin admin = new Admin();
			admin.setCreateTime(rs.getString("createTime"));
			admin.setEmail(rs.getString("email"));
			admin.setId(rs.getString("id"));
			admin.setIp(rs.getString("ip"));
			admin.setLastaccessTime(rs.getString("lastaccessTime"));
			admin.setPasswrod(rs.getString("password"));
			admin.setRole(rs.getString("role"));
			admin.setUsername(rs.getString("username"));
			return admin;
		}
		
	}
}
